package com.every.scheduler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.every.entity.WechatMessage;
import com.every.service.WechatMessageService;
import com.every.utils.BirthdayUtil;
import com.every.utils.RequestUtil;
import com.every.utils.StrUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description: 微信推送消息
 * @author: yh
 * @date: 2022/11/4
 * <p>
 * 消息模板
 * {{firstText.DATA}}
 * <p>
 * 北京时间：{{dateTime.DATA}}
 * 地区：{{address.DATA}}
 * 天气：{{weather.DATA}}
 * 气温：{{temperatureRange.DATA}}
 * 风向：{{windDirection.DATA}}
 * 日出时间：{{sunrise.DATA}}
 * 日落时间：{{sunset.DATA}}
 * 健康小提示：{{healthText.DATA}}
 * <p>
 * {{dialogueText.DATA}}
 */
@Component
@Slf4j
public class WechatTask {
    @Resource
    private WechatMessageService wechatMessageService;
    // 微信开发密钥
    @Value("${wechat.app-id}")
    private String APPID;
    @Value("${wechat.secret}")
    private String SECRET;
    // 天气密钥
    @Value("${wechat.weather.appid}")
    private String WEATHER_APPID;
    @Value("${wechat.weather.appsecret}")
    private String WEATHER_APP_SECRET;
    // 天行数据密钥
    @Value("${wechat.tianxing.key}")
    private String TIAN_XING_KEY;
    // 推送微信openid
    @Value("${wechat.openid}")
    private String openid;
    // 微信模板消息id
    @Value("${wechat.template-id}")
    private String templateId;
    // 点击跳转url
    @Value("${wechat.click-url}")
    private String clickUrl;
    //ROLL平台密钥
    @Value("${wechat.rollTools.app-id}")
    private String ROLL_APP_ID;
    @Value("${wechat.rollTools.app_secret}")
    private String ROLL_APP_SECRET;
    // 获取天气
    private final static String WEATHER_URL = "https://yiketianqi.com/api";
    // 健康小提示
    private final static String HEALTH_URL = "https://api.tianapi.com/healthtip/index";
    // 彩虹屁
    private final static String CAIHONGPI_URL = "https://api.tianapi.com/caihongpi/index";
    // 经典台词
    //private final static String DIALOGUE_URL = "https://api.tianapi.com/dialogue/index";
    // 每日随机段子
//    private final static String JOKES_URL = "https://www.mxnzp.com/api/jokes/list/random";
    // 每日一句
    private final static String RECOMMEND_URL = "https://www.mxnzp.com/api/daily_word/recommend";
    // 土味情话
    private final static String SWEETNOTHINGS_URL = "https://api.lovelive.tools/api/SweetNothings";
    // 网易云热门评论
    private final static String WANGYI_MUSIC_URL = "https://api.uomg.com/api/rand.music?format=json";
    // ROLL天气
    private final static String ROLL_WEATHER_URL = "https://www.mxnzp.com/api/weather/current/临汾";
    // 今日诗词
    private final static String EVERY_DAY_POETRY = "https://v1.jinrishici.com/all.json";

    public Map<String, String> getMessageContent() {
        Map<String, String> resultMap = new HashMap<>();
        // 今日诗词
        JSONObject poetryObject = RequestUtil.getForObject(EVERY_DAY_POETRY);
        if (null != poetryObject) {
            resultMap.put("poetry", poetryObject.getString("content") + "\r\n" + "          ——" + poetryObject.getString("author") + "《" + poetryObject.getString("origin") + "》");
        }
        Map<String, String> paramMap = new HashMap<>();
//        paramMap.put("appid", WEATHER_APPID);
//        paramMap.put("appsecret", WEATHER_APP_SECRET);
//        paramMap.put("city", "临汾");
//        JSONObject getResultObject = RequestUtil.getForObject(WEATHER_URL, null, paramMap);
//        JSONArray dataArray = getResultObject.getJSONArray("data");
//        if (null != dataArray && dataArray.size() > 0) {
//            JSONObject weatherObject = dataArray.getJSONObject(0);
//            resultMap.put("dateTime", weatherObject.getString("date") + " " + weatherObject.getString("week"));
//            resultMap.put("address", getResultObject.getString("city"));
//            resultMap.put("weather", weatherObject.getString("wea"));
//            resultMap.put("temperatureRange", weatherObject.getString("tem2") + "-" + weatherObject.getString("tem1"));
//
//            JSONArray winArray = weatherObject.getJSONArray("win");
//            Set<String> winSet = new HashSet<>();
//            for (int i = 0; i < winArray.size(); i++) {
//                winSet.add(winArray.getString(i));
//            }
//            resultMap.put("windDirection", winSet.stream().collect(Collectors.joining("，")) + "(" + weatherObject.getString("win_speed") + ")");
//            // 日出
//            resultMap.put("sunrise", weatherObject.getString("sunrise"));
//            resultMap.put("sunset", weatherObject.getString("sunset"));
//        }
        // 天气
        if (StringUtils.isBlank(resultMap.get("dateTime"))) {
            paramMap.put("app_id", ROLL_APP_ID);
            paramMap.put("app_secret", ROLL_APP_SECRET);
            JSONObject forObject = RequestUtil.getForObject(ROLL_WEATHER_URL, null, paramMap);
            if ("1".equals(forObject.getString("code"))) {
                JSONObject data = forObject.getJSONObject("data");
                resultMap.put("address", data.getString("address"));
                resultMap.put("temp", data.getString("temp"));
                resultMap.put("windDirection", data.getString("windDirection") + "(" + data.getString("windPower") + ")");
                resultMap.put("humidity", data.getString("humidity"));
                resultMap.put("weather", data.getString("weather"));
            }
        }
        // 获取彩虹屁
        JSONObject caihongResultObject = RequestUtil.getForObject(CAIHONGPI_URL + "?key=" + TIAN_XING_KEY);
        if ("200".equals(caihongResultObject.getString("code"))) {
            JSONArray caihongArray = caihongResultObject.getJSONArray("newslist");
            if (null != caihongArray && caihongArray.size() > 0) {
                resultMap.put("sweetNothings", "" + caihongArray.getJSONObject(0).getString("content"));
            }
        }
        // 健康小提示
        JSONObject healthResultObject = RequestUtil.getForObject(HEALTH_URL + "?key=" + TIAN_XING_KEY);
        if ("200".equals(healthResultObject.getString("code"))) {
            JSONArray healthArray = healthResultObject.getJSONArray("newslist");
            if (null != healthArray && healthArray.size() > 0) {
                resultMap.put("healthText", healthArray.getJSONObject(0).getString("content"));
            }
        }
        try {
            Thread.sleep(1200);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        paramMap.clear();
        paramMap.put("app_id", ROLL_APP_ID);
        paramMap.put("app_secret", ROLL_APP_SECRET);
        // 每日一句
        paramMap.put("count", "1");
        JSONObject recommendResult = RequestUtil.getForObject(RECOMMEND_URL, null, paramMap);
//        log.info("recommend：" + recommendResult.toJSONString());
        if ("1".equals(recommendResult.getString("code"))) {
            JSONArray recommendArray = recommendResult.getJSONArray("data");
            if (recommendArray.size() > 0) {
                resultMap.put("recommend", recommendArray.getJSONObject(0).getString("content"));
            }
        }
        try {
            Thread.sleep(1200);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        // 土味情话
        String forStr = RequestUtil.getForStr(SWEETNOTHINGS_URL);
        if (StringUtils.isNotBlank(forStr)) {
            resultMap.put("firstText", forStr);
        }
        // 网易云热门评论
        List<String> musicType = new ArrayList<>();
        musicType.add("热歌榜");
        musicType.add("新歌榜");
        musicType.add("飙升榜");
        musicType.add("抖音榜");
        musicType.add("电音榜");
        String randomStr = StrUtil.getRandomStr(musicType);
        JSONObject musicObject = RequestUtil.getEncodeFor(WANGYI_MUSIC_URL + "&sort=" + randomStr);
//        log.info("歌曲url：" + WANGYI_MUSIC_URL + "&sort=" + randomStr);
        if ("1".equals(musicObject.getString("code"))) {
            JSONObject data = musicObject.getJSONObject("data");
            if (data != null) {
                resultMap.put("music", data.getString("artistsname") + "《" + data.getString("name") + "》");
                resultMap.put("musicUrl", data.getString("url"));
            }
        }
        // 生日
        String birthday = "1022";
        int i = BirthdayUtil.birthdayDiffer(birthday);
        if(i != 0){
            resultMap.put("birthday", "距离我的的生日还有 " + i + " 天");
        }else{
            // \uD83C\uDF82 \uD83C\uDF82
            resultMap.put("birthday", "今天是你的生日，Happy Birthday To You！");
        }
        // 相遇多少天
        String meetDate = "20221020";
        int meetDay = BirthdayUtil.meetDiffer(meetDate);
        resultMap.put("meet", "今天是我们相遇的第 " + meetDay + " 天");
        return resultMap;
    }

    /**
     * 构造消息内容字体颜色
     *
     * @author: yh
     * @date: 2022/11/11
     */
    public List<WxMpTemplateData> buildData(Map<String, String> contentMap) {
        List<WxMpTemplateData> data = new ArrayList<>();

        // 添加字体颜色
        for (String key : contentMap.keySet()) {
            WxMpTemplateData templateObj = new WxMpTemplateData(key, contentMap.get(key));
            switch (key) {
                // 标题
                case "firstText":
                    templateObj.setColor("#FF7900");
                    break;
                // 相遇
                case "meet":
                    templateObj.setColor("#B22222");
                    break;
                // 天气
                case "weather":
                    templateObj.setColor("#DDA0DD");
                    break;
                // 气温
                case "temp":
                    templateObj.setColor("#A020F0");
                    break;
                // 诗词
//                case "poetry":
//                    templateObj.setColor("#40E0D0");
//                    break;
                // 风向
                case "windDirection":
                    templateObj.setColor("#470DDC");
                    break;
                // 湿度
                case "humidity":
                    templateObj.setColor("#8E236B");
                    break;
                // 生日
                case "birthday":
                    templateObj.setColor("#FF00FF");
                    break;
                // 健康小提示
                case "healthText":
                    templateObj.setColor("#FF0700");
                    break;
                // 彩虹皮
                case "sweetNothings":
                    templateObj.setColor("#4169E1");
                    break;
                // 网易云推荐音乐
                case "music":
                    templateObj.setColor("#E300FF");
                    break;
                // 每日一句
                case "recommend":
                    templateObj.setColor("#87CEEB");
                    break;
                default:
                    break;
            }
            data.add(templateObj);
        }
        return data;
    }

    /**
     * 推送消息
     *
     * @param contentMap 发送内容map
     * @author: yh
     * @date: 2022/11/11
     */
    public void pushMessage(Map<String, String> contentMap) {
        //1，配置
        WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
        wxStorage.setAppId(APPID);
        wxStorage.setSecret(SECRET);
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxStorage);

        // 获取发送内容
        List<WxMpTemplateData> data = buildData(contentMap);

        try {
            String[] openidArr = openid.split(",");
            for (String oid : openidArr) {
                if (StringUtils.isNotBlank(oid)) {
                    Long messageId = wechatMessageService.saveWechatMessage(templateId, oid, JSONObject.toJSONString(data));
                    //2,推送消息
                    WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                            //要推送的用户openid
                            .toUser(oid)
                            //模版id
                            .templateId(templateId)
                            //点击模版消息要访问的网址
                            .url(contentMap.get("musicUrl"))
                            .data(data)
                            .build();
                    wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
                    wechatMessageService.updateState(messageId);
                }
            }
            log.info("-------------------------------推送成功");
        } catch (Exception e) {
            log.error("微信消息推送失败：" + e.getMessage());
        }
    }



    /**
     * 每天早上七点执行一次
     *
     * @author: yh
     * @date: 2022/11/9
     */
    @Scheduled(cron = "0 0 7 * * ?")
    public void morningPush() {
        List<String> list = new ArrayList<>();
        list.add("又是新的一天，希望今天的你比昨天更快乐。早安！");
        list.add("愿你的生活常温暖，日子总是温柔又闪光。早安！");
        list.add("如果事与愿违，就相信上天一定另有安排；所有失去的，都会以另外一种方式归来。相信自己，相信时间不会亏待你。早安！");
        list.add("上了生活的贼船，要做一个快乐的海盗。早安！");
        list.add("别人在努力时，你也在努力，这只叫本分；别人在休息时，你还在努力，这才叫勤奋。早安！");
        list.add("我们要学会珍惜生活的每一天，因为这每一天的开始，都将是我们余下生命之中的第一天。早安！");
        list.add("世界上所有的惊喜和好运，都是你累积的温柔和善良，做一个温柔纯良且内心强大的人，温暖自己，也照亮别人。早安！");
        list.add("每一个平淡的日子都值得尊重，每一个还在身边的人都应该珍惜，愿你眼里有星辰，身边有微风，心中有暖阳。早安！");
        list.add("你要成为光，因为有怕黑的人。早安！");
        String randomStr = StrUtil.getRandomStr(list);

        Map<String, String> messageContent = getMessageContent();
        messageContent.put("firstText", randomStr + "☀️");
        pushMessage(messageContent);
    }

    /**
     * 每天8点-22点整点执行一次
     *
     * @author: yh
     * @date: 2022/11/9
     */
    @Scheduled(cron = "0 0 8-22 * * ?")
    public void everyDayPush() {
        Map<String, String> messageContent = getMessageContent();
        pushMessage(messageContent);
    }

    /**
     * 每天22:30执行一次
     *
     * @author: yh
     * @date: 2022/11/9
     */
    @Scheduled(cron = "0 30 22 * * ?")
    public void nightPush() {
        List<String> list = new ArrayList<>();
        list.add("人生，总有太多的来不及。一眨眼就是一天，一回头就是一年，一转身就是一辈子。珍惜当下。晚安！");
        list.add("记得啊，每晚睡觉前，把白天的丧全部挡在床外，你那么可爱的一个人，可不能带着忧伤入睡。晚安！");
        list.add("阳光早早躲藏起来，留下赤红的晚霞，映照的这个世界如梦似幻。劳累一天的人儿带着月光进入梦乡，梦里梦外都是甜甜的。晚安！");
        list.add("当鸟儿倦了的时候，它会选择飞回巢穴，当人儿累的时候，他会选择回到家里，卸去疲惫的伪装，放松自己心情，原来生活是这样的美好。晚安！");
        list.add("祝今晚好梦！我用手记忆了你的样子，用耳记忆了你的声音，用唇记忆了你的味道，用眼睛记住了你的点点滴滴，用心记忆了你的一切。晚安！");
        list.add("你要相信茫茫人海中，总会有一颗星愿意为你亮着。晚安！");
        list.add("努力做一个温暖的人，不求大富大贵，只求生活简单快乐。过往不恋，未来不迎，当下不负，如此安好。晚安！");
        list.add("很抱歉啊，我白天都没什么机会和你说话。只能憋到晚上给你发句晚安，但你可别小看了这两个字，它可包含着我今天清晨见到的阳光，中午看到的白云，傍晚遇见的微风，包含着我这一天每句想对你说的话。晚安！");
        String randomStr = StrUtil.getRandomStr(list);
        Map<String, String> messageContent = getMessageContent();

        messageContent.put("firstText", randomStr + "\uD83D\uDCA4  ");
        pushMessage(messageContent);
    }
}
